package com.tangqiao;

import java.awt.image.BufferedImage;

public class FENGenerator {

	public int baseX;
	public int baseY;

	public FENGenerator(int baseX, int baseY) {
		this.baseX = baseX;
		this.baseY = baseY;
	}

	public String getFEN(BufferedImage image) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 10; ++i) {
			for (int j = 0; j < 9; ++j) {
				int tox = baseX + 48 * j;
				int toy = baseY + 48 * i;
				int v = generate(image, tox - 5, toy - 5, tox + 5, toy + 5 );
				sb.append(DataMap.getChar(v));
			}
			if (i != 9) sb.append('/');
		}
		String res = sb.toString();
		res = res.replaceAll("111111111", "9");
		res = res.replaceAll("11111111", "8");
		res = res.replaceAll("1111111", "7");
		res = res.replaceAll("111111", "6");
		res = res.replaceAll("11111", "5");
		res = res.replaceAll("1111", "4");
		res = res.replaceAll("111", "3");
		res = res.replaceAll("11", "2");
		int k1 = res.indexOf('k');
		int k2 = res.indexOf('K');
		char myChess;
		if (k1 < k2) myChess = 'w';
		else {
			sb = new StringBuffer(res);
			for (int i=0; i<sb.length(); ++i) {
				char ch = sb.charAt(i);
				if (ch>='a' && ch <='z') ch = Character.toUpperCase(ch);
				else if (ch>='A' && ch <='Z') ch = Character.toLowerCase(ch);
				sb.setCharAt(i, ch);
			}
			res = sb.toString();
			myChess = 'w';
		}
		return "position fen " +res + " " + myChess + " - - 0 1";
	}
	
	private int generate(BufferedImage image, int x1, int y1, int x2, int y2) {
		int res;
		int cnt = 0;
		for (int i=x1; i<x2; ++i)
			for (int j=y1; j<y2; ++j) {
				int v = image.getRGB(i, j);
				if ( v == DataGenerator.BLACK) res = 3;
				else if (v == DataGenerator.RED) res = 1;
				else res = 0;
				cnt += res;
			}
		return cnt;
	}
}
